<?php

namespace App\Http\Controllers;

use App\Models\Config;
use App\Models\Record;
use App\Models\Sign;
use Carbon\Carbon;
use Illuminate\Http\Request;

class SignController extends Controller
{
    //

    public function index(Request $request)
    {
        $user = $request->user();
        $start = $request->get('startTime');
        $end = $request->get('endTime');

        $start = Carbon::parse($start / 1000)->toDateString();
        $end = Carbon::parse($end / 1000)->format('Y-m-d 23:59:59');

        $res = (new Sign)->getUserSignByTime($user->id, $start, $end);

        return $this->response(['isSign' => $res]);
    }

    public function store(Request $request)
    {
        $user = $request->user();

        $config = Config::query()->where('key','signIntegral')->first();
        if (!$config) return $this->response(['success' => false],'未配置签到参数。');
        $integral = $config->val;

        $start = Carbon::today()->toDateTimeString();
        $end = Carbon::today()->format('Y-m-d 23:59:59');

        $isSign = $res = (new Sign)->getUserSignByTime($user->id, $start, $end);
        if ($isSign) return $this->response(['success' => false],'已经签到过了。');

        // 签到记录
        Sign::query()->create([
            'user_id'   => $user->id,
            'integral'  => $integral,
            'sign_time' => Carbon::today()
        ]);

        // 给用户增加积分
        $user->incIntegral($integral);

        // 添加积分记录
        Record::query()->create([
            'mode'=> 1,
            'name'=> '签到积分',
            'integral'=> $integral,
            'user_id'=> $user->id
        ]);

        return $this->response(['success' => true, 'integral' => $integral], '签到成功！');
    }
}
